//

// jQuery UI draggable 适配移动端

var moveFlag = 0; // 是否移动的flag
stape = 0;
var a;
// /iPad|iPhone|Android/.test( navigator.userAgent ) &&
(function ($) {
    var proto = $.ui.mouse.prototype, _mouseInit = proto._mouseInit;
    $.extend(proto, {
        _mouseInit: function () {
            this.element.bind("touchstart." + this.widgetName, $.proxy(this, "_touchStart"));
            _mouseInit.apply(this, arguments);
        }, _touchStart: function (event) {
            this.element.bind("touchmove." + this.widgetName, $.proxy(this, "_touchMove")).bind("touchend." + this.widgetName, $.proxy(this, "_touchEnd"));
            this._modifyEvent(event);
            $(document).trigger($.Event("mouseup"));
            //reset mouseHandled flag in ui.mouse
            this._mouseDown(event);
            //console.log(this);
            //return false;

            //--------------------touchStart do something--------------------
            console.log("i touchStart!");

        }, _touchMove: function (event) {
            moveFlag = 1;
            this._modifyEvent(event);
            this._mouseMove(event);

            //--------------------touchMove do something--------------------
            console.log("i touchMove!");

        }, _touchEnd: function (event) {
            // 主动触发点击事件
            if (moveFlag == 0) {
                var evt = document.createEvent('Event');
                evt.initEvent('click', true, true);
                this.handleElement[0].dispatchEvent(evt);
            }
            this.element.unbind("touchmove." + this.widgetName).unbind("touchend." + this.widgetName);
            this._mouseUp(event);
            moveFlag = 0;

            //--------------------touchEnd do something--------------------
            console.log("i touchEnd!");

        }, _modifyEvent: function (event) {
            event.which = 1;
            var target = event.originalEvent.targetTouches[0];
            event.pageX = target.clientX;
            event.pageY = target.clientY;
        }
    });
})(jQuery);


function two_char(n) {
    return n >= 10 ? n : "0" + n;
}

function time_fun() {
    var sec = 0;
    a = setInterval(function () {
        sec++;
        var date = new Date(0, 0)
        date.setSeconds(sec);
        var h = date.getHours(), m = date.getMinutes(), s = date.getSeconds();
        document.getElementById("mytime").innerText = two_char(h) + ":" + two_char(m) + ":" + two_char(s);
    }, 1000);
}
window.onload=time_fun();
var imagePuzzle = {
    startGame: function (images) {    //开始游戏的函数
        this.setImage(images);
        $('#playPanel').show();
        $('#sortable').randomize();   //随机打乱图片
        this.enableSwapping('#sortable li');
    },
    enableSwapping: function (elem) {   //交换图片的函数方法
        $(elem).draggable({
            snap: '#droppable',
            snapMode: 'outer',
            revert: "invalid",
            helper: "clone"
        });
        $(elem).droppable({
            drop: function (event, ui) {
                var $dragElem = $(ui.draggable).clone();
                y=$(this).offset();
                x=$(ui.draggable).offset();
                var change=$('input[name="tRadio"]:checked').val();
                if( (change==2)&&((Math.abs(x.top-y.top)>102)||(Math.abs(x.left-y.left)>102)||(Math.abs(x.left-y.left)==(Math.abs(x.top-y.top))))){
                    alert("只能交换相邻的图片，请按照规则进行游戏");
                }
                else{
                    $dragElem.replaceAll(this);
                    $(this).replaceAll(ui.draggable);
                    imagePuzzle.enableSwapping(this);
                    imagePuzzle.enableSwapping($dragElem);
                    stape=stape+1;
                    document.getElementById("div1").innerHTML = stape;
                }
                currentList = $('#sortable > li').map(function (i, el) {
                    return $(el).attr('data-value');
                });
                if (isSorted(currentList)) {
                    var tmpStep = stape;
                    var tmpTime = $("#mytime").html();
                    $('#actualImageBox').empty().html($('#gameOver').html());
                    $('#newPhoto').empty().html($('#Tihuan').html());
                    var tmpName = prompt("请输入你的名字");
                    tmpName = (tmpName.length == 0) ? "未知" : tmpName;
                    upData(tmpTime, tmpName,dbId);
                    stape = 0;
                    clearInterval(a);
                }
            }
        });
    },

    setImage: function (images) {
        var now = new Date();
        var number = now.getSeconds();
        var image = images[Math.floor(Math.random(number) * images.length)];
        //   $('#imgTitle').html(image.title);
        $('#actualImage').attr('src', image.src);
        $('#imgIntroduce').html(image.introduce);
        $('#sortable').empty();
        for (var i = 0; i < 16; i++) {
            var xpos = (33.33 * (i % 4)) + '%';
            var ypos = (33.33 * Math.floor(i / 4)) + '%';
            var li = $('<li class="item" data-value="' + (i) + '"></li>').css({
                'background-image': 'url(' + image.src + ')',
                'background-position': xpos + ' ' + ypos
            });
            $('#sortable').append(li);
        }
        $('#sortable').randomize();
    }

};
function isSorted(arr) {
    for (var i = 0; i < arr.length - 1; i++) {
        if (arr[i] != i)
            return false;
    }
    return true;
}

$.fn.randomize = function (selector) {
    var $elems = selector ? $(this).find(selector) : $(this).children(),
        $parents = $elems.parent();

    $parents.each(function () {
        $(this).children(selector).sort(function () {
            return Math.round(Math.random()) - 0.5;
        }).remove().appendTo(this);
    });
    return this;
};

function upData(time, name,imgId) {
    var data = {"user_grace": time, "username": name,"image_id":imgId};
    $.post("/puzzle_game/index.php/Home/saveData", data, function (d, s) {
        if(d>0){
            alert("保存成功！");
        }
    })
}



/**/
function locking(){
    document.all.ly.style.display="block";
    document.all.ly.style.width=document.body.clientWidth;
    document.all.ly.style.height=document.body.clientHeight;
    document.all.Layer2.style.display='block';
}
function Lock_CheckForm(theForm){
    document.all.ly.style.display='none';document.all.Layer2.style.display='none';
    return false;
}


/**/
var box;
var count=1;
window.onload=function(){
    box=document.getElementById("img_box");

    var left=document.getElementById("left");
    var right=document.getElementById("right");
    left.addEventListener("click",_left);
    right.addEventListener("click",_right);
}
function _right(){
    var dis=0;
    if(count<3){
        dis=count*360;
    }else{
        dis=0;
        count=0;
    }
    box.style.left="-"+dis+"px";
    count+=1;
}
function _left(event){
    var dis=0;
    if(count>1){
        dis=(2-count)*360;
    }else{
        dis=-2*360;
        count=4;
    }
    box.style.left=dis+"px";
    count-=1;
}
